import 'dart:async';
import 'package:flutter/material.dart';
import 'package:grasp_flutter_app/page/welcome_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'page/main_page.dart';
import 'utils/local/app_localizations_delegate.dart';
import 'utils/utils.dart';

void main() {
  runZoned(() {
    runApp(FlutterReduxApp());
    PaintingBinding.instance.imageCache.maximumSize = 100;
    Provider.debugCheckInvalidValueType = null;
  }, onError: (Object obj, StackTrace stack) {
    print(obj);
    print(stack);
  });
}

class FlutterReduxApp extends StatelessWidget {
  /// 创建Store，引用 GSYState 中的 appReducer 实现 Reducer 方法
  /// initialState 初始化 State
  final store = new Store<SysState>(
    SysState.appReducer,
    middleware: SysState.middleware,

    ///初始化数据
    initialState: new SysState(
        themeData: Utils.getThemeData(Styles.primarySwatch),
        locale: Locale('zh', 'CH')),
  );

  FlutterReduxApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    /// 通过 StoreProvider 应用 store
    Common.appUIStyle();

    return new StoreProvider(
      store: store,
      child: new StoreBuilder<SysState>(builder: (context, store) {
        return new MaterialApp(
            /// 多语言实现代理
            localizationsDelegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              AppLocalizationsDelegate.delegate,
            ],
            locale: store.state.locale,
            supportedLocales: [store.state.locale],
            theme: store.state.themeData,
            onGenerateTitle: (context) {
              return Utils.getLocale(context).name;
            },
            routes: {
              WelcomePage.name: (context) {
                store.state.platformLocale = WidgetsBinding.instance.window.locale;
                return WelcomePage();
              },
              MainPage.name: (context) {
                return new BasePage(child: Utils.pageContainer(new MainPage()));  // 包一层
              },
            });
      }),
    );
  }
}

class BasePage extends StatefulWidget {
  final Widget child;

  BasePage({Key key, this.child}) : super(key: key);

  @override
  State<BasePage> createState() {
    return new _BasePageState();
  }
}

class _BasePageState extends State<BasePage> {
  StreamSubscription stream;

  @override
  Widget build(BuildContext context) {
    return new StoreBuilder<SysState>(builder: (context, store) {
      ///通过 StoreBuilder 和 Localizations 实现实时多语言切换
      return new Localizations.override(
        context: context,
        locale: store.state.locale,
        child: widget.child,
      );
    });
  }

  @override
  void initState() {
    super.initState();

    ///Stream演示event bus
    stream = eventBus.on<HttpErrorEvent>().listen((event) {
      errorHandleFunction(event.code, event.message);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (stream != null) {
      stream.cancel();
      stream = null;
    }
  }

  ///网络错误提醒
  void errorHandleFunction(int code, message) {
    switch (code) {
      case Consts.NETWORK_ERROR:
        Utils.toast(Utils.getLocale(context).networkError);
        break;
      case 401:
        Utils.toast(Utils.getLocale(context).networkError_401);
        break;
      case 403:
        Utils.toast(Utils.getLocale(context).networkError_403);
        break;
      case 404:
        Utils.toast(Utils.getLocale(context).networkError_404);
        break;
      case Consts.NETWORK_TIMEOUT:
        Utils.toast(Utils.getLocale(context).networkErrorTimeout);
        break;
      default:
        Utils.toast(Utils.getLocale(context).networkErrorUnknown +  " " + message);
        break;
    }
  }
}
